#include <stdio.h>
#include <sys/msg.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>

#define MAXSIZE 128

typedef struct msmg
{
    long type;
    char ch[MAXSIZE];
}msmg,*fmsmg;

void initialize(fmsmg msg,int type){

    (*msg).type = type;//类型
    
    scanf("%s",(*msg).ch);
    


    return;
}


int main(int argc,const char* argv){

    //key
    key_t key = ftok("./app",'a');
    if(key < 0){
        perror("ftok err");
        return -1;
    }
    printf("key:%#x\n",key);



    int msgid = msgget(key,IPC_CREAT | IPC_EXCL | 0666);
    if(msgid <= 0){
        if(errno == EEXIST){
            msgid = msgget(key,0666);
        }else{
            perror("msgget err");
            return -1;
        }
    }

    printf("shmid:%d\n",msgid);

    msmg msg;
    ssize_t size = sizeof(msg) - sizeof(long);
    signal(SIGQUIT,SIG_DFL);//检测到SIGQUIT信号就退出

    pid_t pid=-1;
    pid = fork();
    if(pid < 0){
        perror("fork err");
        msgctl(msgid,IPC_RMID,NULL);
        return -1;
    }else if(pid == 0){

        while(1){
            msgrcv(msgid,&msg,size,2,0);//接收消息
            if(strcmp(msg.ch,"quit") == 0){
                kill(getppid(),SIGQUIT);//通知父进程结束
                break;
            }
            printf("rose:%s\n",msg.ch);
        }
        
        return 0;
        
    }else{

        while(1){
            initialize(&msg,1);
            msgsnd(msgid,&msg,size,0);//发送消息
            if(strcmp(msg.ch,"quit") == 0){
                kill(pid,SIGQUIT);//通知子进程结束
                break;
            }    
        }
        
        wait(NULL);
        msgctl(msgid,IPC_RMID,NULL);
    }



    return 0;
}